package com.work;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("cglib动态代理：日志......");
        System.out.println(method.getName());
        Object o = null;
        try{
            o =  method.invoke(targetClass.newInstance(), args);
        }catch (Exception e){
        }
        return o;
    }

    private Class targetClass;

    public Object getProxy(Class targetClass){
        this.targetClass = targetClass;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetClass);
        enhancer.setCallback(this);
        return enhancer.create();
    }
}
